/* api */
import * as TaskApi from '@src/api/TaskApi.ts';
import { getCardFieldAll } from '@src/api/ProductV2Api';
import { getLogisticsQuotaDetail } from '@src/api/FieldApi';
import { getRichTextContent } from '@src/api/SystemApi'
/* mixin */
import ReceiptMixin from '../TaskReceiptMixin';
import QualityMixin from '../Edit/quality-mixin';
import RuleReceiptMixin from '@src/modules/task/view/components/TaskReceipt/Edit/rule-receipt-mixin.js';

/* components */
import ReceiptCommonTable from './components/ReceiptCommonTable';
import TaskReceiptEditView from '../Edit/TaskReceiptEditView';
import LogisticsDialog from './components/LogisticsDialog';
import FaultTable from '@src/modules/task/editAllot/components/PartSeviceList/components/FaultTable.vue';

/* image */
import { getLocalesOssUrl } from '@src/util/assets'
const APPROVING_IMG = getLocalesOssUrl('/task/approving.png');
import { isArray } from '@src/util/type';
import i18n from '@src/locales'
// 国际化灰度
import useFormMultiLanguage from '@hooks/useFormMultiLanguage'
const { internationalGray } = useFormMultiLanguage()

import { getRootWindow } from '@src/util/dom';
import { handlerMaterialList } from '@src/modules/task/view/components/materialUtil.js';
import _ from 'lodash'

export default {
  name: 'task-receipt-detail-view',
  mixins: [ReceiptMixin, QualityMixin, RuleReceiptMixin],
  props: {
    formCellCount: {
      type: Number,
      default: 1
    }
  },
  data() {
    return {
      checking: false, // 检查状态
      hasQuota: false, // 是否能查看
      partField: [], // 安装产品和安装位置字段 博立定制
      sparepartColums: [{
        label: i18n.t('common.form.preview.sparepart.colum2'),
        field: 'serialNumber'
      }, {
        label: i18n.t('common.base.name'),
        field: 'name'
      }, {
        label: i18n.t('common.form.preview.sparepart.colum3'),
        field: 'primaryType'
      }, 
      {
        label: i18n.t('common.form.preview.sparepart.colum4'),
        field: 'standard'
      },{
        label: i18n.t('common.form.preview.sparepart.colum5'),
        field: 'repertoryName'
      }, {
        label: i18n.t('common.form.preview.sparepart.colum7'),
        field: 'salePrice',
        width: '88px'
      }, {
        label: i18n.t('common.form.preview.sparepart.colum6'),
        field: 'number',
        width: '88px'
      }, {
        label: i18n.t('common.form.preview.sparepart.colum8'),
        field: 'total',
        width: '88px'
      }],
      materialColums: [], // 自定义的物料核销表头
      settlementCurrency: 'CNY',
      internationalGray,
      sparePartsReturnExpenseFields: [], // 备件返还表头
    }
  },
  computed: {
    /** 
    * @description 回执自定义字段
    * 判断非自定义回执、自定义回执
    */
    fields() {
      return this.notCustom ? this.notCustomFields : this.shareData.receiptFields;
    },
    /** 
    * @description 回执详情数据
    */
    receiptData() {
      return this.initData?.receiptTaskForRead || {};
    },
    /** 
    * @description 备件、服务项目、折扣费用数据集合
    * 物料核销、物料申领数据集合
    */
    expenseSheet() {
      return this.initData.receiptExpenseSheetForRead || {};
    },
    /** 
    * @description 显示合计
    * 1.配置了服务项目或备件就显示费用合计
    * 2.新增了物料核销
    */
    hasExpense() {
      let { sparepart, serviceIterm, materialVerifyEliminate } = this.form;
      return (sparepart && isArray(sparepart)) || (serviceIterm && isArray(serviceIterm)) || (materialVerifyEliminate && isArray(materialVerifyEliminate));
    },
    /** 
    * @description 是否完成审批中
    */
    isFinishApproving() {
      return this.shareData.isFinishApproving;
    },
    /** 
    * @description 物料配置
    */
    materialInfo() {
      return this.initData?.materialInfo || {}
    },
    /**
    * @description 是否显示质保字段
    */
    showWarrantyStatus() {
      let { showWarrantyStatus } = this.materialInfo || {}
      return showWarrantyStatus
    },
    /** 
    * @description 是否显示[编辑回执]按钮
    * 情况一：
    * 1.是审批状态且有工单审批权限 
    * 2.工单设置里的完成工单的"允许审批人修改回执表单"开关打开
    * 3.工单状态是完成工单审批
    * 4.工单配置开启了启用回执编辑
    * 5.如果关闭了开始工单 状态为accepted 也允许编辑 详见bug:19111
    * 2022/08/11 bugfix:17841 删除条件4. 审批状态下开启了"允许审批人修改回执表单"则允许编辑回执
    
    * 情况二：
    * 1. 不是审批状态
    * 2. 且 允许编辑工单canEditTask
    * 3. 且 工单状态不是costed和closed
    * 4. 且 工单配置开启了启用回执编辑
    */
    allowEditReceipt() {
      let stateArr = ['costed', 'closed'];
      let { state, inApprove } = this.task;
      let approveEditReceipt =  this.taskType.flowSetting.finish.approveEditReceipt
      return ((inApprove == 1 && this.allowApprove && (state == 'processing' || state == 'accepted') && approveEditReceipt ) 
        || (inApprove != 1 && this.initData.canEditTask && this.receiptConfig.editReceipt && stateArr.indexOf(state) == -1));
    },
    /** 
    * @description 支付方式
    */
    paymentMethod() {
      return this.receiptData?.attribute?.paymentMethod || this.task?.attribute?.paymentMethod || '';
    },
    /** 
    * @description 返还方式
    */
    returnType() {
      return this.form?.attribute?.returnType
    },
    /** 
    * @description 公司
    */
    returnTypeCompany() {
      return this.form?.attribute?.company
    },
    /** 
    * @description 物流编号
    */
    returnTypeCode() {
      return this.form?.attribute?.code
    },
    // 物料核销固定字段
    materialVerifyEliminateColums() {
      let colums = [
        {
          label: i18n.t('common.currency.exchangeMethod'),
          field: 'exchangeMethod',
          minWidth: '140px'
        },
        {
          label: i18n.t('common.currency.exchangeRate'),
          field: 'exchangeRate',
          minWidth: '100px'
        },
        {
          label: i18n.t('common.currency.conversionPrice'),
          field: 'conversionPrice',
          minWidth: '100px'
        },
        {
          label: i18n.t('common.form.preview.materialReturn.tableLabel7'),
          field: 'warrantyStatus'
        },
        {
          label: i18n.t('common.form.preview.sparepart.colum9'),
          field: 'warehouseName',
        }, 
        {
          label: i18n.t('common.form.preview.sparepart.colum12'),
          field: 'positionName',
        },
        {
          label: i18n.t('common.form.preview.sparepart.colum20'),
          field: 'number',
        },
        {
          label: i18n.t('common.form.preview.sparepart.colum22'),
          field: 'replacedMaterial',
          width:120
        },
        {
          label: i18n.t('common.form.preview.sparepart.colum24'),
          field: 'snList',
          width:120
        },
        {
          label: i18n.t('common.form.preview.sparepart.colum23'),
          field: 'replacedSnList',
          width:120
        },
        {
          label: this.$t('common.label.batchNum'),
          formType: 'text',
          field: 'batchNumber',
          isSystem: 1
        },
        {
          label: this.$t('common.form.preview.materialVerifyEliminate.settleType'),
          field: 'settleType',
          width: 120
        },
      ]
      if(!this.showWarrantyStatus) {
        colums = colums.filter(item => item.field !== 'warrantyStatus')
      }

      if (!this.isBatchPeriod) {
        colums = colums.filter(item => item.field !== 'batchNumber')
      }

      if(this.isSettlementRule) {
        colums.splice(2, 0, {
          label: i18n.t('common.zhongqi.title1'),
          field: 'settlementRules',
        })
      }
      // 国际化灰度未开启
      if(!this.internationalGray) {
        let arr = ['exchangeMethod', 'exchangeRate', 'conversionPrice']
        colums = colums.filter(item => !(arr.includes(item.field)))
      }

      // 未开启配件结算方式
      if (!this.isShowSettleType) {
        colums = colums.filter(item => item.field !== 'settleType')
      }

      return colums
    },
    relationMaterialFields() {
      let materialReturnFields = this.fields.find(item => item.fieldName == 'materialReturn') || {};
      let newFields = (materialReturnFields?.setting?.materialFields || []).map(item => {
        return {
          ...item,
          label: item.displayName,
          field: item.fieldName
        }
      })
      return newFields;
    },
    materialReturnColums() {
      let colums = [
        ...this.relationMaterialFields,
        {
          label: i18n.t('common.form.preview.materialReturn.tableLabel7'),
          field: 'warrantyStatus'
        },
        {
          label: i18n.t('common.form.preview.materialReturn.tableLabel8'),
          field: 'warehouseName',
        }, 
        {
          label: i18n.t('common.form.preview.materialReturn.tableLabel9'),
          field: 'positionName',
        },
        {
          label: i18n.t('common.form.preview.materialReturn.tableLabel10'),
          field: 'number',
        },
        {
          label: i18n.t('common.form.preview.materialReturn.tableLabel12'),
          width:120,
          field: 'snList',
        },
        {
          label: i18n.t('common.form.preview.materialReturn.tableLabel13'),
          width:180,
          field: 'recordNo',
        }
      ]
      if(!this.showWarrantyStatus) {
        colums = colums.filter(item => item.field !== 'warrantyStatus')
      }

      // 完成回执-物料返还 是否隐藏终端销售价
      if(!this.serviceProviderShowPrice) {
        colums = colums.filter(item => item.field !== 'salePrice' && item.field !== 'conversionPrice')
      }
      return colums
    },

    serviceColums() {
      let colums = [{
        label: i18n.t('common.form.preview.sparepart.colum2'),
        field: 'serialNumber'
      }, 
      {
        label: i18n.t('common.base.name'),
        field: 'name'
      }, {
        label: i18n.t('common.form.preview.sparepart.colum3'),
        field: 'primaryType'
      }, {
        label: i18n.t('common.form.preview.sparepart.colum7'),
        field: 'salePrice',
        width: '88px'
      }, {
        label: i18n.t('common.form.preview.sparepart.colum6'),
        field: 'number',
        width: '88px'
      }, {
        label: i18n.t('common.form.preview.sparepart.colum8'),
        field: 'total',
        width: '88px'
      }]

      if(this.isShowSettlementRules) {
        colums.splice(2, 0, {
          label: i18n.t('common.zhongqi.title1'),
          field: 'settlementRules',
        },
        {
          label: i18n.t('common.form.preview.qualityField.label3'),
          field: 'serviceQualityStatus'
        })
      }
      // TODO 国际化灰度开启
      if(this.internationalGray) {
        colums.splice(colums.length-2, 0, {
          label:i18n.t('common.currency.exchangeMethod'),
          field: 'exchangeMethod',
          minWidth: '140px'
        },
        {
          label:i18n.t('common.currency.exchangeRate'),
          field: 'exchangeRate',
          minWidth: '100px'
        },
        {
          label:i18n.t('common.currency.conversionPrice'), // 换算后单价
          field: 'conversionPrice',
          minWidth: '100px'
        })
      }

      // 完成回执-服务项目 是否隐藏单价和小计
      if(!this.serviceProviderShowPrice) {
        colums = colums.filter(item => item.field !== 'salePrice' && item.field !== 'total' && item.field !== 'conversionPrice')
      }

      // 服务项目折扣相关灰度
      if(this.isServiceItemDiscountSettings){
        // 先找到单价的下标，找到后再在其后面拼折扣费用
        colums.forEach((item,index) => {
          if(item.field === 'salePrice'){
            colums.splice(index + 1, 0, {
              label: this.$t('kaili.list.reductionFee'),
              field: 'reductionFee',
            })
          }
        })
      }
      return colums;
    },
    // 批次号灰度
    isBatchPeriod() {
      const RootWindow = getRootWindow(window)
      return RootWindow.grayAuth?.BATCH_PERIOD
    },
    // 物料核销 是否开启配件结算方式 
    isShowSettleType() {
      // 是否开启慈星物料核销灰度
      const RootWindow = getRootWindow(window)
      const isCiXingMaterialGray = RootWindow.grayAuth?.CIXING_MATERIAL_SETTLE

      // 是否开启配件结算方式
      const materialVerifyEliminateField = this.fields.find(field => field.fieldName == 'materialVerifyEliminate') || {}
      const isShowSettleType = materialVerifyEliminateField?.setting?.isShowSettleType || false

      return isCiXingMaterialGray && isShowSettleType
    },
  },
  methods: {
    // 查询是否还有剩余可使用次数
    async checkQuota() {
      try {
        if (this.checking) return;
        this.checking = true;
        this.hasQuota = await getLogisticsQuotaDetail();
        return this.hasQuota;
      } catch (err) {
        const message = (err && err.message) || i18n.t('common.form.tip.logistics.tips5');
        this.$alert(message);
      } finally {
        this.checking = false;
      }
    },
    // 查看物流信息
    async handleViewDetail() {
      try {
        if (!this.hasQuota) return; // 没有次数直接不允许点
        const has = await this.checkQuota();
        if (!has) return;
        this.$refs.logisticsDialog.dialogShow = true
      } catch (error) {
        console.error('查询余额:', error);
      }
    },
    /** 
    * @description 审批图片
    */
    getApprovingImg() {
      return APPROVING_IMG;
    },
    /** 
    * @description 打开弹窗
    */
    async openDialog() {
      // 工单上备件用的库和当前租户备件库配置不同
      if (this.initData.isRepertoryDiff) return this.$platform.alert(i18n.t('task.tip.receiptTip10'));

      // 支付完成提示
      if(this.isPaySuccess) this.$platform.alert(i18n.t('task.tip.receiptTip11'));

      // this.$refs.taskReceiptEdit.openDialog('edit');
      this.$emit('edit');
    },
    getPriceShow(value) {
      if(this.internationalGray) {
        return `${value} ${this.settlementCurrency}`
      }
      return value
    }
  },
  async mounted() {
    try {
      // 查询物流可点击次数
      this.checkQuota();
      // 在线支付成功
      // TODO：payment服务已废弃，拿不到数据，暂时注释
      // if (this.isPaySuccess) await this.getPaymentMethodDetail();

      const expenseSheet = _.cloneDeep(this.expenseSheet)
      const receiptData = _.cloneDeep(this.receiptData)
      let { sparePartsExpense = [], serviceExpense = [], materialExpense = [], materialReturnExpense = [], discountExpense = {}, settlementCurrency, sparePartsReturnExpense = [] } = expenseSheet;
      let { attachment = [], attribute = {}, receiptContent } = receiptData;
      
      // 初始化默认值
      this.form = receiptData;
      this.form.currencyType = settlementCurrency || 'CNY'
      this.settlementCurrency = settlementCurrency
      // 处理回执信息
      this.fields.forEach(field => {
        let { fieldName } = field;

        // 回执附件
        if(fieldName === 'receiptAttachment') {
          this.form[fieldName] = attachment.filter(img => img.receipt);
        }
        // 客户签名
        else if(fieldName === 'systemAutograph') {
          this.form[fieldName] = attribute[fieldName];
        }
        // 备件
        else if(fieldName === 'sparepart') {
          // 计算修改后的单价
          sparePartsExpense.forEach(item => {
            let modifiedPrice = isNaN(item.modifiedPrice) ? 0 : item.modifiedPrice;
            let nowPrice = Number(item.salePrice) + Number(modifiedPrice);
            item.salePrice = nowPrice.toFixed(2);
          })

          this.form[fieldName] = sparePartsExpense;
        }
        // 备件返还
        else if(fieldName === 'sparePartsReturnExpense') {
          // 自定义设置的表头
          this.sparePartsReturnExpenseFields = (field?.setting?.sparePartFieldList || []).map(item => {
            item.label = item.displayName || item.label
            return item
          });
          this.form[fieldName] = sparePartsReturnExpense;
        }
        // 服务项目
        else if(fieldName === 'serviceIterm') {
          // 计算修改后的单价
          serviceExpense.forEach(item => {
            let modifiedPrice = isNaN(item.modifiedPrice) ? 0 : item.modifiedPrice;
            let nowPrice = Number(item.salePrice) + Number(modifiedPrice);
            item.salePrice = nowPrice.toFixed(2);
            item.salePriceCurrency = item.modifiedPriceCurrency
          })

          this.form[fieldName] = (serviceExpense || []).map(item => {
            const { attribute, ...other } = item;
            return {
              ...attribute,
              ...other
            }
          });
        }
        // 物料核销
        else if(fieldName === 'materialVerifyEliminate') {
          // 自定义设置的表头
          this.materialColums = [...(field?.setting?.materialFields || []), ...this.materialVerifyEliminateColums].map(item => {
            item.label = item.displayName || item.label
            return item
          });
          if(!this.showWarrantyStatus) {
            this.materialColums = this.materialColums.filter(item => item.field !== 'warrantyStatus')
          }

          if (!field?.setting?.replacedMaterialCheck) {
            // 表单配置没有选中 是否需要填写被替换物料，则表头不展示
            this.materialColums = this.materialColums.filter(item => item.field !== 'replacedMaterial')
          }

          // 完成回执-物料核销 是否隐藏终端销售价
          if(!this.serviceProviderShowPrice) {
            this.materialColums = this.materialColums.filter(item => item.field !== 'salePrice' && item.field !== 'conversionPrice')
          }

          this.form[fieldName] = handlerMaterialList(materialExpense, this.materialColums).map(item => {
            const { attribute, ...other } = item;
            return {
              ...attribute,
              ...other
            }
          })
        }
        // 物料返还
        else if(fieldName === 'materialReturn') {
          this.form[fieldName] = handlerMaterialList(materialReturnExpense, this.materialReturnColums)
        }
        // 回执内容
        else if(fieldName === 'receiptContent') {
          this.form[fieldName] = receiptContent || '';
        }

      });

      // 折扣费用
      this.form.disExpense = discountExpense?.salePrice || 0;

      // 获取是否有安装产品和安装位置 目前只有博立有数据 其它的数据为空
      const result = await TaskApi.getExpensePartField()
      if (result.code == 0) {
        this.partField = result.result || []
      }
      if (this.partField.length) {
        this.partField.forEach((part, ind) => {
          this.form.sparepart.forEach(_sparepart => {
            _sparepart.products = this.form.products
            if (part.fieldName == 'installProductId') {
              _sparepart.installProductId = _sparepart.attribute ? _sparepart.attribute.installProductId : ''
            } else if (part.fieldName == 'installPosition') {
              _sparepart.installPosition = _sparepart.attribute ? _sparepart.attribute.installPosition : ''
            }
          })
          // 更新sparepartColums
          let index = 2
          if (part.fieldName == 'installPosition') {
            index = 3
          }
          this.sparepartColums.splice(index, 0, {
            label: part.displayName,
            field: part.fieldName
          })
        })
      }
      if(this.initData?.taskType?.options?.replaceProductCard){
        let cardInfoIds = []
        this.form.sparepart.forEach(_sparepart => {
          if (_sparepart.cardInfoAttribute) {
            Object.assign(_sparepart,_sparepart.cardInfoAttribute)
          }
          _sparepart.replaceCardInfoId && cardInfoIds.push(_sparepart.replaceCardInfoId)
        })

        
        cardInfoIds.length > 0 && getCardFieldAll({cardInfoIds:cardInfoIds}).then(res=>{
          if(res.success){
            //过滤附件字段
            let filterRes = res.result.filter(item=>{
              return item.formType !== 'attachment'
            })
            let tempFilterArr = filterRes?.filter(item=>{
              return item.formType != 'relationReplacementPart' && item.fieldName != 'part'
            })
            let tempArr = tempFilterArr.map(item=>{
              return {
                label: item.displayName,
                formType: item.formType,
                field: item.fieldName
              }
            })
            this.sparepartColums.splice(-3, 0, ...tempArr)
            console.log(this.sparepartColums)
          }else{
            console.log(res.message)
          }
        })
      }

      // 完成回执-备件 是否隐藏单价和小计
      if(!this.serviceProviderShowPrice) {
        this.sparepartColums = this.sparepartColums.filter(item => item.field !== 'salePrice' && item.field !== 'total' && item.field !== 'conversionPrice')
      }

    } catch (e) {
      console.error('error ', e)
    }
    
    await this.fetchRuleList()
  },
  components: {
    [ReceiptCommonTable.name]: ReceiptCommonTable,
    [TaskReceiptEditView.name]: TaskReceiptEditView,
    [LogisticsDialog.name]: LogisticsDialog,
    [FaultTable.name]: FaultTable

  }
}
